package lock.lock.deadLock;

/**
 * @author: zhangyi
 * @date: 2018/12/17 22:30
 * @description:
 */
public class DaedLock {
    static Object o1 = new Object();
    static Object o2 = new Object();
    public static void main(String[] args) {
        LockDemo1 lockDemo1 = new LockDemo1(o1,o2);
        LockDemo2 lockDemo2 = new LockDemo2(o1,o2);
        lockDemo1.start();
        lockDemo2.start();
    }

    static class LockDemo1 extends Thread{
        Object o1;
        Object o2;
        public LockDemo1(Object o1, Object o2){
            this.o1 = o1;
            this.o2 = o2;
        }
        @Override
        public void run() {
            while(true){
                synchronized (DaedLock.o1) {
                    System.out.println("获取当前线程的锁:o1");
                    //为了可以模拟另一个线程抢占锁住o2
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (DaedLock.o2) {
                        System.out.println("获取当前线程的锁:o2");
                    }

                }
            }
        }
    }

    static class LockDemo2 extends Thread{
        Object o1;
        Object o2;
        public LockDemo2(Object o1, Object o2){
            this.o1 = o1;
            this.o2 = o2;
        }
        @Override
        public void run() {
            while (true){
                synchronized (DaedLock.o2) {
                    System.out.println("获取当前线程的锁:o2");
                    synchronized (DaedLock.o1) {
                        System.out.println("获取当前线程的锁:o1");
                    }

                }
            }
        }
    }

}